package com.huadao.cart_ccs.common.inputControl;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class MaxDecimalTextWatch implements TextWatcher {

    private int max;
    //精确到几位小数
    private int decimalCount;
    private EditText editText;
    private boolean isAutoMax;
    private NumberMaxAttention numberMaxAttention;

    public MaxDecimalTextWatch(int max,int decimalCount) {
        this.max = max;
        this.decimalCount=decimalCount;
    }

    public MaxDecimalTextWatch(int max,int decimalCount, EditText editText, boolean isAutoMax) {
        this.max = max;
        this.decimalCount=decimalCount;
        this.editText = editText;
        this.isAutoMax = isAutoMax;
    }

    public MaxDecimalTextWatch(int max,int decimalCount, EditText editText, boolean isAutoMax, NumberMaxAttention numberMaxAttention) {
        this.max = max;
        this.decimalCount=decimalCount;
        this.editText = editText;
        this.isAutoMax = isAutoMax;
        this.numberMaxAttention = numberMaxAttention;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            return;
        }
        try {
            double current = Double.parseDouble(s.toString());
            if (current > max) {
                if (isAutoMax) {
                    String maxStr = String.valueOf(max);
                    s.clear();
                    s.append(maxStr);
                }
                if(numberMaxAttention!=null){
                    numberMaxAttention.onNumberMax(String.valueOf(max),editText);
                }
            }
            int dotIndex = s.toString().indexOf(".");
            if (dotIndex != -1 && (s.length() - decimalCount - 1 > dotIndex)) {
                s.delete(dotIndex + decimalCount + 1, s.length());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
